package com.cm.sys.framework.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.cm.sys.framework.aop.NotCheckIP;
import com.cm.sys.framework.application.ApiResponseCode;
import com.cm.sys.framework.execption.BusinessException;
import com.cm.sys.framework.utils.IpAddressUtil;

/***
 * ip拦截器
 * 
 * @author yxq18
 *
 */

@Component
public class IPInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(IPInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws IOException {
        logger.info("--进入了ip拦截器过滤白名单-------" + request.getServletPath());

        // 过滤ip,若用户在白名单内，则放行
        String ipAddress = IpAddressUtil.getIpAddress(request);
        logger.info("进入的ip=====【{}】=====", ipAddress);

        if (handler instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod)handler;
            if (h.getMethodAnnotation(NotCheckIP.class) != null) {
                return true;
            }
        }

        if (!StringUtils.isEmpty(ipAddress)) {
            String ip = "127.0.0.1";
            String publicIP = "112.97.167.225";
            // 同一局域网不拦截 要拦截把下面的提上去
            if (ipAddress.substring(0, 3).equals("10.") || ipAddress.substring(0, 4).equals("172.")
                || ipAddress.substring(0, 4).equals("192.")) {
                return true;
            }
            if (publicIP.equals(ipAddress)) {
                return true;
            }
            if (!(ip.equals(ipAddress))) {
                throw new BusinessException(ApiResponseCode.NO_IP.getCode(), ApiResponseCode.NO_IP.getMessage());
            }
        }
        return true;
    }

    /*
     * 处理请求完成后视图渲染之前的处理操作
     * 通过ModelAndView参数改变显示的视图，或发往视图的方法
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) {

    }

    /*
     * 视图渲染之后的操作
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
        throws Exception {

    }
}
